package com.zl.learning.thread.future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class TestFutureTask {

    static class Test1 {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            FutureTask<Integer> ft = new FutureTask<>(() -> {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 1;
            });
            new Thread(ft).start();
            System.out.println("wait futureTask.....");
            int v = ft.get();
            System.out.println(v);
        }
    }

    static class Test2 {
        public static void main(String[] args) {
            CallableThreadTest ctt = new CallableThreadTest();
            FutureTask<Integer> ft = new FutureTask<>(ctt);
            for (int i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName() + " 的循环变量i的值" + i);
                if (i == 20) {
                    new Thread(ft, "有返回值的线程").start();
                }
            }
            try {
                System.out.println("子线程的返回值：" + ft.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

        }
    }

    static class CallableThreadTest implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            int i = 0;
            for (; i < 100; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            return i;
        }
    }
}
